<?php
namespace app\sys\controller;

use my\wechat\QyWeChat;

class Open
{
    private $_wechat = null;

    public $error = '';

    private function wechat()
    {
        $c = [
            'appid' => c('wx_appid'),
            'appsecret' => c('wx_appsecret')
        ];

        if ($this->_wechat == null)
            $this->_wechat = new QyWeChat($c);

        return $this->_wechat;
    }

    public function login()
    {
        if (config('app_is_release')) {
            return $this->qywxLogin();
        }

        return view();
    }

    private function qywxLogin()
    {
        $auth_code = input('auth_code');
        if (!empty($auth_code)) {
//            $ret = $this->wechat()->getLoginInfo($auth_code);
//
//            //记住用户cookie
//            $user_id = $ret['user_info']['userid'];
//
//            $callback = cookie('login_callback');
//            cookie('login_callback', null);

            return redirect(url('Open/login') . "?auth_code={$auth_code}");
        }

        //登录成功回调地址
        $callback = input('server.HTTP_REFERER');
        cookie('login_callback', $callback);

        //跳转到微信企业号授权登录页面
        $url = request()->url(true);
        $wx_login = 'https://qy.weixin.qq.com/cgi-bin/loginpage?corp_id=' . c('wx_appid') . '&redirect_uri=' . urlencode($url) . '&usertype=member';
        return '<script type="text/javascript">window.location.href="' . $wx_login . '";</script>';
    }
}